import {PlusOutlined} from '@ant-design/icons';
import {Button, Drawer, Form, message} from 'antd';
import React, {useState, useRef} from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import type {ProColumns, ActionType} from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import {
  ModalForm,
  ProFormDigit, ProFormSelect, ProFormSwitch,
  ProFormText,
} from '@ant-design/pro-form';
import {isSuccess} from "@/utils/utils";
import {DictionaryManager} from "@/services/api-functions";
import {DictionaryMod} from "@/services/api-types";

const handleEdit = async (fields: any, select: any) => {
  try {
    const rpo: DictionaryMod = {
      id: select?.id ?? '',
      name: fields.name,
      enabling: fields.enabling?1:0,
      sortNum: fields.sortNum,
      key: fields.key,
      parentId: fields.parentId !== '0' ? fields.parentId : '',
    }
    if (isSuccess((select && select.id ? (await DictionaryManager.mod(rpo)) : (await DictionaryManager.add(rpo)))?.code)) {
      message.success('保存成功');
      return true;
    }
    return false;
  } catch (error) {
    return false;
  }
};


const DictionaryList: React.FC<any> = () => {

  const [formRef] = Form.useForm()
  const [visible, handleVisible] = useState<boolean>(false);
  const [detailVisible, setDetailVisible] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const childActionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<any>();
  const [parent, setParent] = useState<any>();

  const initFiledValue = (current: any = undefined, callBack: Function) => {
    if (current) {
      setCurrentRow(current)
      formRef?.setFieldsValue({
        name: current.name,
        parentId: current.parentId,
        key: current.key,
        sortNum: current.sortNum,
        enabling: !!current.enabling,
      })
      if (callBack) {
        callBack()
      }
    }
  }

  const columns: ProColumns[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      ellipsis: true,
      hideInSearch: true,
      fixed: 'left',
    },
    {
      title: '名称',
      dataIndex: 'name',
      hideInForm: true,
      render: (dom, record) => {
        return (
          <a onClick={() => {
            setDetailVisible(true)
            setParent(record)
            if(childActionRef.current){
              childActionRef.current.reload();
            }
          }}>
            {dom}
          </a>
        );
      },
    },
    {
      title: 'KEY',
      dataIndex: 'key',
      ellipsis: true,
      hideInSearch: true,
    },{
      title: '父级ID',
      dataIndex: 'parentId',
      ellipsis: true,
      hideInSearch: true,
      render: (_, record) => record?.parentId ? '暂无' : record?.parentId
    },
    {
      title: '排序值',
      dataIndex: 'sortNum',
      width: 150,
      hideInSearch: true,
    },
    {
      title: '操作者',
      dataIndex: 'userName',
      ellipsis: true,
      width: 250,
      hideInSearch: true,
    },
    {
      title: '修改时间',
      dataIndex: 'gmtModified',
      valueType: 'dateTime',
      width: 170,
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '创建时间',
      dataIndex: 'gmtCreate',
      valueType: 'dateTime',
      width: 170,
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      hideInSearch: true,
      hideInForm: true,
      fixed: 'right',
      render: (_, record) => [
        /*<a key="edit"
           onClick={() => initFiledValue(record, () => handleVisible(true))}
        >编辑</a>,*/
        <a key="edit"
           onClick={() => {
             setDetailVisible(true)
             setParent(record)
             if(childActionRef.current){
               childActionRef.current.reload();
             }
           }}
        >详情</a>,
      ],
    },
  ];

  const childColumn: ProColumns[] = [
    {
      title: '名称',
      dataIndex: 'name',
      hideInForm: true,
      fixed: 'left',
      render: (dom, record) => {
        return (
          <a onClick={() => initFiledValue(record, () => handleVisible(true))}>
            {dom}
          </a>
        );
      },
    },
    {
      title: 'KEY',
      dataIndex: 'key',
      ellipsis: true,
      hideInSearch: true,
    },
    {
      title: '排序值',
      dataIndex: 'sortNum',
      width: 100,
      hideInSearch: true,
    },
    {
      title: '操作者',
      dataIndex: 'userName',
      ellipsis: true,
      width: 170,
      hideInSearch: true,
    },
    {
      title: '修改时间',
      dataIndex: 'gmtModified',
      valueType: 'dateTime',
      width: 170,
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      hideInSearch: true,
      hideInForm: true,
      fixed: 'right',
      render: (_, record) => [
        <a key="edit"
           onClick={() => initFiledValue(record, () => handleVisible(true))}
        >编辑</a>,
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable<any, any>
        headerTitle='字典列表'
        actionRef={actionRef}
        rowKey="key"
        search={{labelWidth: 120,}}
        request={async (params) => {

          const {data: {data, total}, code}: any = await DictionaryManager.page(params);

          return {data: data || [], success: isSuccess(code), total: isSuccess(code) ? total : 0};
        }}
        columns={columns}
        scroll={{ x: 1300 }}
      />
      <ModalForm
        title={currentRow ? `编辑【${currentRow?.name}】` : `添加字典`}
        width="750px"
        form={formRef}
        visible={visible}
        onVisibleChange={v => {
          handleVisible(v)
          if (!v) {
            formRef?.resetFields()
            setCurrentRow(undefined)
          }
        }}
        onFinish={async (value) => {
          // @ts-ignore
          if (await handleEdit(value as any, currentRow)) {
            handleVisible(false);
            formRef?.resetFields()
            setCurrentRow(undefined)
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >
        <ProFormSelect label='父级字典' name='parentId' required initialValue={'0'} rules={[{required: true, message: '请设置父级字典',},]}
                       request={async (params) => {
                         const {code, data} = await DictionaryManager.page({
                           current: 1,
                           pageSize: 20,
                           name: params.keyWords ?? '',
                         })
                         return [{label: `暂无`, value: '0'}, ...(isSuccess(code) ? (data.data ?? []).map((item: any) => {
                           const {name, key, id} = item
                           return {label: `${name}(${key})`, value: id}
                         }) : [])]
                       }} showSearch disabled/>
        <ProFormText label='字典名称' required rules={[{required: true, message: '请填写字典名称',},]} name="name"/>
        <ProFormText label='KEY' required rules={[{required: true, message: '请填写字典KEY',},]} name="key"/>
        <ProFormSwitch label='是否启用' unCheckedChildren='不启用' checkedChildren='启用' initialValue={true} name='enabling' required/>
        <ProFormDigit label='排序值' name='sortNum' required initialValue={1} rules={[{required: true, message: '请填输入排序值',},]}/>
      </ModalForm>
      <Drawer
        width={870}
        placement="right"
        onClose={() => setDetailVisible(false)}
        visible={detailVisible && !visible}
        title={parent?.name}
      >
        <ProTable<any, any>
          headerTitle='二级字典列表'
          actionRef={childActionRef}
          rowKey="key"
          search={false}
          toolBarRender={() => [
            <Button
              type="primary"
              key="primary"
              onClick={() => {
                handleVisible(true);
                formRef?.setFieldsValue({
                  parentId: parent.id,
                })
              }}>
              <PlusOutlined/> 添加二级字典
            </Button>,
          ]}
          request={async (params) => {

            const {data, code}: any = await DictionaryManager.detail({...params, parentId: parent.id});

            return {data: data || [], success: isSuccess(code), total: isSuccess(code) ? data.length : 0};
          }}
          columns={childColumn}
          scroll={{ x: 1300 }}
        />
      </Drawer>
    </PageContainer>
  );
};
export default DictionaryList;
